from . import models
from django.db.models import Q
from django.contrib.auth.backends import ModelBackend
from django_redis import get_redis_connection



def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    token:jwt字符串
    user:当前登录用户对象
    request:当前请求对象
    """
    # 购物车数量
    conn = get_redis_connection('cart')
    cart_length = conn.hlen(f'cart_{user.id}')

    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'cart_length': cart_length,
    }


#多条件登录
def get_user_by_account(account):
    """
    根据帐号获取user对象
    :param account: 账号，可以是用户名，也可以是手机号
    :return: User对象 或者 None
    """
    try:

        user = models.User.objects.filter(Q(username=account)|Q(phone=account)).first()
    except models.User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        #if user is not None and user.check_password(password) :
        if user is not None and user.check_password(password) and user.is_authenticated:
            #user.is_authenticated是看他有没有权限的，这里可以不加上它
            return user
